<template>
  <el-container style="height: 100vh">
    <!-- 侧边栏 -->
    <Sidebar @menu-select="handleMenuSelect" />

    <!-- 主容器：包含顶部导航栏和主内容 -->
    <el-container direction="vertical">
      <!-- 顶部导航栏 -->
      <Header :page-title="currentPageTitle" :user-name="userName"></Header>

      <!-- 主内容区域 -->
      <el-main style="padding: 20px">
        <Content :active-content="activeContent" />
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
  import { ref, onMounted } from 'vue'
  import { validateToken, setAuthToken } from '@/api/userApi'
  import Sidebar from '@/components/Sidebar.vue'
  import Header from '@/components/Header.vue'
  import Content from '@/components/Content.vue'

  const activeContent = ref('1')
  const currentPageTitle = ref('首页')
  let userName = ref('')

  onMounted(async () => {
    userName.value = localStorage.getItem('username') || sessionStorage.getItem('username') || ''
    console.log('[HomeView] 设置 userName = ', userName)
    const token = localStorage.getItem('token') || sessionStorage.getItem('token')
    console.log('用户token:', token)

    if (!token) {
      console.log('[HomeView] 未找到token，跳转到登录页')
      router.push('/login')
      return
    }

    try {
      console.log('[HomeView] 开始验证token')
      // 先设置Token到请求头
      setAuthToken(token)
      // 调用后端接口验证token是否有效
      const result = await validateToken(token)

      if (result.valid) {
        console.log('[HomeView] token有效, 验证通过')
      } else {
        console.log('[HomeView] token无效, 验证失败')
        ElMessage.error('您的会话已失效, 请重新登录')
        // 清除所有存储的token
        clearAllTokens()
        router.push('/login')
      }
    } catch (error) {
      console.error('[HomeView] 验证token出错:', error)
      ElMessage.error('验证登录状态失败，请重新登录')
      clearAllTokens()
      router.push('/login')
    }
  })

  // 清除所有存储的token
  const clearAllTokens = () => {
    localStorage.removeItem('token')
    localStorage.removeItem('rememberMe')
    localStorage.removeItem('account')
    localStorage.removeItem('username')
    sessionStorage.removeItem('token')
    sessionStorage.removeItem('username')
  }

  const handleMenuSelect = (index) => {
    activeContent.value = index
    if (index === '1') {
      currentPageTitle.value = '首页'
    } else if (index === '2') {
      currentPageTitle.value = '个人账单'
    } else if (index === '3') {
      currentPageTitle.value = '个人信息'
    }
  }
</script>
